Page({
  data: {
    isEdit: false,
    taskIndex: -1,
    taskName: '',
    taskDesc: '',
    taskLevel: 1,
    taskType: '1',
    taskTypeName: '',
    imagePath: '',
    taskLevels: [
      { id: 1, name: '简单' },
      { id: 2, name: '中等' },
      { id: 3, name: '困难' }
    ],
    taskTypes: [
      { id: '1', name: '文字题' },
      { id: '2', name: '视频题' },
      { id: '3', name: '照片题' },
      { id: '4', name: '选择题' }
    ]
  },

  onLoad(options) {
    if (options.task) {
      const task = JSON.parse(options.task);
      const taskIndex = parseInt(options.index);
      const taskTypeObj = this.data.taskTypes.find(item => item.id === task.taskType) || {};
      this.setData({
        isEdit: true,
        taskIndex,
        taskName: task.taskName,
        taskDesc: task.taskDesc,
        taskLevel: task.taskLevel,
        taskType: task.taskType,
        taskTypeName: taskTypeObj.name || '',
        imagePath: task.imagePath || ''
      });
    }
  },

  // 输入处理函数
  onNameInput(e) {
    this.setData({ taskName: e.detail.value });
  },

  onDescInput(e) {
    this.setData({ taskDesc: e.detail.value });
  },

  onLevelChange(e) {
    const index = e.detail.value;
    this.setData({ 
      taskLevel: this.data.taskLevels[index].id 
    });
  },

  onTypeChange(e) {
    const index = e.detail.value;
    const selectedType = this.data.taskTypes[index];
    this.setData({ 
      taskType: selectedType.id,
      taskTypeName: selectedType.name
    });
  },

  // 选择图片
  chooseImage() {
    wx.chooseImage({
      count: 1,
      sizeType: ['compressed'],
      sourceType: ['album', 'camera'],
      success: (res) => {
        const tempFilePath = res.tempFilePaths[0];
        this.uploadImage(tempFilePath);
      }
    });
  },

  // 上传图片
  uploadImage(tempFilePath) {
    wx.showLoading({
      title: '上传中...',
    });

    // 获取存储的cookies
    const cookies = wx.getStorageSync('cookies');
    if (!cookies) {
      wx.hideLoading();
      wx.showToast({
        title: '请先登录',
        icon: 'none'
      });
      return;
    }

    // 上传图片到服务器
    wx.uploadFile({
      url: getApp().globalData.config.baseUrl[getApp().globalData.config.env] + getApp().globalData.config.apiPath.upload.image,
      filePath: tempFilePath,
      name: 'file',
      header: {
        'Cookie': cookies
      },
      success: (res) => {
        const data = JSON.parse(res.data);
        if (data.errorCode === '000000') {
          this.setData({
            imagePath: data.data.url
          });
        } else {
          wx.showToast({
            title: '上传失败',
            icon: 'none'
          });
        }
      },
      fail: () => {
        wx.showToast({
          title: '上传失败',
          icon: 'none'
        });
      },
      complete: () => {
        wx.hideLoading();
      }
    });
  },

  // 验证表单
  validateForm() {
    const { taskName, taskDesc, taskLevel, taskType } = this.data;

    if (!taskName || taskName.trim().length === 0) {
      wx.showToast({
        title: '请输入任务名称',
        icon: 'none'
      });
      return false;
    }

    if (!taskDesc || taskDesc.trim().length === 0) {
      wx.showToast({
        title: '请输入任务描述',
        icon: 'none'
      });
      return false;
    }

    if (!taskLevel) {
      wx.showToast({
        title: '请选择任务级别',
        icon: 'none'
      });
      return false;
    }

    if (!taskType) {
      wx.showToast({
        title: '请选择任务类型',
        icon: 'none'
      });
      return false;
    }

    return true;
  },

  // 保存任务
  saveTask() {
    if (!this.validateForm()) return;

    console.log('保存任务时的data:', this.data);

    const taskData = {
      taskName: this.data.taskName,
      taskDesc: this.data.taskDesc,
      taskLevel: this.data.taskLevel,
      taskType: this.data.taskType,
      imagePath: this.data.imagePath
    };

    console.log('保存任务时的taskData:', taskData);

    const eventChannel = this.getOpenerEventChannel();
    if (this.data.isEdit) {
      eventChannel.emit('editTask', taskData);
    } else {
      eventChannel.emit('addTask', taskData);
    }

    wx.navigateBack();
  }
}); 